// 新闻聚合系统 - 主要JavaScript文件

// 全局变量
let currentPage = 1;
let currentSortBy = 'date'; // 'date' | 'hot'
let isLoadingMore = false; // 无限下拉加载状态
let reachedEnd = false; // 是否到达末页
const pageSize = 12; // 每页显示12条新闻
let allNews = [];
let filteredNews = [];
let currentUser = null;
let totalNewsCount = 0; // 总新闻数
let totalPages = 0; // 总页数

// 搜索相关变量
let searchMode = false; // 是否在搜索模式
let currentSearchParams = {}; // 当前搜索参数
let searchResults = [];
let searchPage = 1;
let searchTotalPages = 1;
let searchTotalResults = 0;
let searchSuggestionsTimeout = null;

// 收藏相关变量
let currentFavoritesPage = 1;
let allFavorites = [];
let totalFavoritesCount = 0;
let totalFavoritesPages = 0;
let currentView = 'news'; // 'news' 或 'favorites'
let currentNewsDetail = null; // 当前正在查看的新闻
// 推荐相关变量
let recommendations = [];
let recPage = 1;
let recTotal = 0;
let recTotalPages = 1;
const recPageSize = 6; // 每页显示6条推荐

// 新闻内容缓存
let newsContentCache = new Map(); // 用于缓存已获取的完整内容
const CACHE_EXPIRY_TIME = 30 * 60 * 1000; // 缓存30分钟

// 缓存管理函数
function getCachedContent(newsId) {
    const cached = newsContentCache.get(newsId);
    if (!cached) return null;
    
    // 检查是否过期
    if (Date.now() - cached.timestamp > CACHE_EXPIRY_TIME) {
        newsContentCache.delete(newsId);
        return null;
    }
    
    return cached.content;
}

function setCachedContent(newsId, content) {
    newsContentCache.set(newsId, {
        content: content,
        timestamp: Date.now()
    });
    
    // 限制缓存大小，保持最近100条记录
    if (newsContentCache.size > 100) {
        const firstKey = newsContentCache.keys().next().value;
        newsContentCache.delete(firstKey);
    }
}

function clearExpiredCache() {
    const now = Date.now();
    for (const [newsId, cached] of newsContentCache.entries()) {
        if (now - cached.timestamp > CACHE_EXPIRY_TIME) {
            newsContentCache.delete(newsId);
        }
    }
}

// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查Font Awesome是否加载成功
    checkFontAwesome();
    
    // 检查用户登录状态
    checkLoginStatus();
    
    // 从 URL 获取当前状态
    const currentCategory = getCurrentCategoryFromURL();
    const currentPage = getCurrentPageFromURL();
    
    // 更新分类选择器状态
    updateCategorySelectors(currentCategory);
    
    // 加载新闻
    loadNews(currentPage, currentCategory);
    
    // 绑定事件监听
    bindEventListeners();
    // 初始化推荐（登录后显示）
    initRecommendationsIfNeeded();
    
    // 定期清理过期缓存（每10分钟执行一次）
    setInterval(clearExpiredCache, 10 * 60 * 1000);
});

// 检查Font Awesome是否加载成功
function checkFontAwesome() {
    const testElement = document.createElement('i');
    testElement.className = 'fa fa-heart';
    testElement.style.position = 'absolute';
    testElement.style.left = '-9999px';
    document.body.appendChild(testElement);
    
    setTimeout(() => {
        const computedStyle = window.getComputedStyle(testElement, ':before');
        if (computedStyle.getPropertyValue('font-family').indexOf('FontAwesome') === -1) {
            console.warn('Font Awesome 加载失败，使用备用图标');
            // 为所有fa类添加备用样式
            const style = document.createElement('style');
            style.textContent = `
                .fa:before { 
                    font-family: Arial, sans-serif !important;
                    content: '●' !important;
                }
                .fa-heart:before { content: '♥' !important; }
                .fa-heart-o:before { content: '♡' !important; }
                .fa-newspaper-o:before { content: '📰' !important; }
                .fa-bars:before { content: '☰' !important; }
                .fa-angle-right:before { content: '›' !important; }
                .fa-caret-down:before { content: '▼' !important; }
                .fa-sign-out:before { content: '→' !important; }
                .fa-magic:before { content: '✨' !important; }
                .fa-lock:before { content: '🔒' !important; }
                .fa-spinner:before { content: '↻' !important; }
                .fa-check:before { content: '✓' !important; }
                .fa-times:before { content: '×' !important; }
            `;
            document.head.appendChild(style);
        }
        document.body.removeChild(testElement);
    }, 100);
}

// ========== 搜索功能实现 ==========

// 执行搜索
function searchNews(params = {}) {
    // 标记进入搜索模式
    searchMode = true;
    currentSearchParams = params;
    
    // 显示搜索结果页面
    switchToSearchView();
    
    // 显示加载状态
    const container = document.getElementById('search-results-container');
    container.innerHTML = `
        <div class="col-span-full flex justify-center items-center py-16">
            <div class="text-center">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mb-4"></div>
                <p class="text-neutral">正在搜索...</p>
            </div>
        </div>
    `;
    
    // 构建查询参数
    const queryParams = new URLSearchParams({
        page: params.page || 1,
        per_page: pageSize,
        ...params
    });
    
    // 发送搜索请求
    fetch(`/api/search-news?${queryParams}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: 搜索失败`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Search results:', data);
            
            if (!data || !data.news) {
                throw new Error('无效的搜索结果格式');
            }
            
            // 更新搜索结果状态
            searchResults = data.news;
            searchPage = data.pagination?.page || 1;
            searchTotalPages = data.pagination?.pages || 1;
            searchTotalResults = data.pagination?.total || 0;
            
            // 渲染搜索结果
            renderSearchResults();
            updateSearchStats();
            updateSearchPaginationControls();
            
            // 保存搜索历史（如果用户已登录）
            if (currentUser && params.keyword) {
                saveSearchHistory(params.keyword);
            }
        })
        .catch(error => {
            console.error('搜索错误:', error);
            container.innerHTML = `
                <div class="col-span-full text-center py-16">
                    <p class="text-red-500">搜索失败: ${error.message}</p>
                    <button onclick="switchToNewsView()" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition">
                        返回新闻列表
                    </button>
                </div>
            `;
        });
}

// 渲染搜索结果
function renderSearchResults() {
    const container = document.getElementById('search-results-container');
    container.innerHTML = '';
    
    if (searchResults.length === 0) {
        container.innerHTML = `
            <div class="col-span-full text-center py-16">
                <div class="text-center">
                    <i class="fa fa-search text-6xl text-gray-300 mb-4"></i>
                    <p class="text-neutral">没有找到相关新闻</p>
                    <button onclick="switchToNewsView()" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition">
                        返回新闻列表
                    </button>
                </div>
            </div>
        `;
        return;
    }
    
    searchResults.forEach(news => {
        const card = createSearchResultCard(news);
        container.appendChild(card);
    });
}

// 创建搜索结果卡片（支持关键词高亮）
function createSearchResultCard(news) {
    const card = document.createElement('div');
    card.className = 'bg-white rounded-xl shadow-sm overflow-hidden card-hover';
    card.setAttribute('data-id', news.id);
    
    // 格式化日期
    const date = new Date(news.display_publish_time || news.published_date || news.created_at);
    const formattedDate = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    // 收藏状态
    const isFavorited = news.is_favorited === 1;
    const favoriteIcon = isFavorited ? 'fa-heart' : 'fa-heart-o';
    const favoriteColor = isFavorited ? 'text-red-500' : 'text-gray-400';
    
    // 高亮关键词
    const keyword = currentSearchParams.keyword || '';
    const highlightedTitle = highlightKeyword(news.title, keyword);
    const highlightedSummary = highlightKeyword(news.summary || (news.content ? news.content.substring(0, 100) + '...' : '无内容'), keyword);
    
    card.innerHTML = `
        <div class="p-5">
            <div class="flex items-center justify-between text-xs text-neutral mb-3">
                <div class="flex items-center">
                    <span>${news.source_name || '未知来源'}</span>
                    <span class="mx-2">•</span>
                    <span>${formattedDate}</span>
                    <span class="ml-2 px-2 py-0.5 bg-light rounded-full">${getCategoryName(news.category)}</span>
                </div>
                ${currentUser ? `
                    <button class="favorite-btn hover:scale-110 transition-transform" data-news-id="${news.id}">
                        <i class="fa ${favoriteIcon} ${favoriteColor} text-lg"></i>
                    </button>
                ` : ''}
            </div>
            <h3 class="font-semibold text-lg mb-2 line-clamp-2 hover:text-primary transition cursor-pointer news-title">
                ${highlightedTitle}
            </h3>
            <p class="text-neutral text-sm mb-4 line-clamp-3">
                ${highlightedSummary}
            </p>
            <button class="text-primary text-sm hover:underline view-detail-btn">
                查看详情 <i class="fa fa-angle-right ml-1"></i>
            </button>
        </div>
    `;
    
    // 绑定事件
    card.querySelector('.view-detail-btn').addEventListener('click', () => showNewsDetail(news.id));
    card.querySelector('.news-title').addEventListener('click', () => showNewsDetail(news.id));
    
    if (currentUser) {
        card.querySelector('.favorite-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            toggleNewsFavorite(news.id, e.target.closest('.favorite-btn'));
        });
    }
    
    return card;
}

// 关键词高亮
function highlightKeyword(text, keyword) {
    if (!keyword || !text) return text;
    
    const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    return text.replace(regex, '<mark class="bg-yellow-200 px-1 rounded">$1</mark>');
}

// 切换到搜索视图
function switchToSearchView() {
    currentView = 'search';
    searchMode = true;
    
    // 显示/隐藏页面
    document.getElementById('news-page').classList.add('hidden');
    document.getElementById('favorites-page').classList.add('hidden');
    document.getElementById('search-results-page').classList.remove('hidden');
    
    // 更新标签样式（取消所有高亮）
    document.getElementById('news-tab').classList.remove('bg-primary', 'text-white');
    document.getElementById('news-tab').classList.add('text-gray-500');
    document.getElementById('favorites-tab').classList.remove('bg-primary', 'text-white');
    document.getElementById('favorites-tab').classList.add('text-gray-500');
}

// 更新搜索统计信息
function updateSearchStats() {
    const searchInfo = document.getElementById('search-info');
    const keyword = currentSearchParams.keyword || '';
    searchInfo.innerHTML = `
        搜索 "<span class="font-semibold">${keyword}</span>" 共找到 <span class="font-semibold">${searchTotalResults}</span> 条结果
    `;
}

// 更新搜索分页控制
function updateSearchPaginationControls() {
    const prevBtn = document.getElementById('search-prev-page');
    const nextBtn = document.getElementById('search-next-page');
    const showingRange = document.getElementById('search-showing-range');
    const totalResults = document.getElementById('search-total-results');
    
    prevBtn.disabled = searchPage <= 1;
    nextBtn.disabled = searchPage >= searchTotalPages;
    
    const start = (searchPage - 1) * pageSize + 1;
    const end = Math.min(searchPage * pageSize, searchTotalResults);
    showingRange.textContent = searchTotalResults > 0 ? `${start}-${end}` : '0-0';
    totalResults.textContent = searchTotalResults;
}

// 搜索分页控制
function goToSearchPrevPage() {
    if (searchPage > 1) {
        const newParams = { ...currentSearchParams, page: searchPage - 1 };
        searchNews(newParams);
        document.getElementById('search-results-container').scrollIntoView({ behavior: 'smooth' });
    }
}

function goToSearchNextPage() {
    if (searchPage < searchTotalPages) {
        const newParams = { ...currentSearchParams, page: searchPage + 1 };
        searchNews(newParams);
        document.getElementById('search-results-container').scrollIntoView({ behavior: 'smooth' });
    }
}

// 执行快速搜索
function performQuickSearch() {
    const keyword = document.getElementById('search-input').value.trim();
    if (!keyword) {
        alert('请输入搜索关键词');
        return;
    }
    
    // 隐藏搜索建议
    hideSearchSuggestions();
    
    const params = {
        keyword: keyword,
        page: 1
    };
    
    searchNews(params);
}

// 执行移动端搜索
function performMobileSearch() {
    const keyword = document.getElementById('mobile-search-input').value.trim();
    if (!keyword) {
        alert('请输入搜索关键词');
        return;
    }
    
    // 隐藏搜索建议
    hideSearchSuggestions();
    
    const params = {
        keyword: keyword,
        page: 1
    };
    
    searchNews(params);
}

// 执行高级搜索
function performAdvancedSearch() {
    const form = document.getElementById('advanced-search-form');
    const formData = new FormData(form);
    
    const params = {
        keyword: formData.get('keyword') || '',
        scope: formData.get('scope') || 'all',
        source: formData.get('source') || '',
        category: formData.get('category') || '',
        date_from: formData.get('date_from') || '',
        date_to: formData.get('date_to') || '',
        sort_by: formData.get('sort_by') || 'relevance',
        page: 1
    };
    
    // 过滤空值
    Object.keys(params).forEach(key => {
        if (!params[key]) delete params[key];
    });
    
    if (!params.keyword && !params.source && !params.category) {
        alert('请至少输入一个搜索条件');
        return;
    }
    
    // 关闭模态框
    hideModal('advanced-search-modal');
    
    // 隐藏搜索建议
    hideSearchSuggestions();
    
    // 执行搜索
    searchNews(params);
}

// 获取搜索建议
function getSearchSuggestions(keyword) {
    if (!keyword || keyword.length < 2) {
        hideSearchSuggestions();
        return;
    }
    
    // 清除之前的延时
    if (searchSuggestionsTimeout) {
        clearTimeout(searchSuggestionsTimeout);
    }
    
    // 延时执行以避免频繁请求
    searchSuggestionsTimeout = setTimeout(() => {
        fetch(`/api/search-suggestions?q=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success' && data.suggestions.length > 0) {
                    showSearchSuggestions(data.suggestions);
                } else {
                    hideSearchSuggestions();
                }
            })
            .catch(error => {
                console.error('获取搜索建议失败:', error);
                hideSearchSuggestions();
            });
    }, 300);
}

// 显示搜索建议
function showSearchSuggestions(suggestions) {
    const container = document.getElementById('search-suggestions');
    container.innerHTML = '';
    
    suggestions.forEach(suggestion => {
        const item = document.createElement('div');
        item.className = 'px-4 py-2 hover:bg-gray-100 cursor-pointer border-b border-gray-100 last:border-b-0';
        item.innerHTML = `
            <div class="flex items-center">
                <i class="fa fa-search text-gray-400 mr-3"></i>
                <span>${suggestion.text}</span>
            </div>
        `;
        
        item.addEventListener('click', () => {
            document.getElementById('search-input').value = suggestion.text;
            hideSearchSuggestions();
            performQuickSearch();
        });
        
        container.appendChild(item);
    });
    
    container.classList.remove('hidden');
}

// 隐藏搜索建议
function hideSearchSuggestions() {
    document.getElementById('search-suggestions').classList.add('hidden');
}

// 清空搜索并返回新闻列表
function clearSearch() {
    searchMode = false;
    currentSearchParams = {};
    searchResults = [];
    document.getElementById('search-input').value = '';
    switchToNewsView();
}

// 绑定所有事件监听
function bindEventListeners() {
    // 移动端菜单切换
    document.getElementById('mobile-menu-btn').addEventListener('click', function() {
        const mobileMenu = document.getElementById('mobile-menu');
        mobileMenu.classList.toggle('hidden');
    });
    
    // 页面切换
    document.getElementById('news-tab').addEventListener('click', () => switchToNewsView());
    document.getElementById('favorites-tab').addEventListener('click', () => switchToFavoritesView());
    document.getElementById('favorites-btn').addEventListener('click', () => switchToFavoritesView());
    document.getElementById('mobile-favorites-btn').addEventListener('click', () => {
        switchToFavoritesView();
        document.getElementById('mobile-menu').classList.add('hidden');
    });
    
    // 分类筛选
    document.getElementById('mobile-category-filter').addEventListener('change', function() {
        filterNewsByCategory(this.value);
        updateNavCategoryButtons(this.value);
        updateNavCategorySelector(this.value);
        document.getElementById('mobile-menu').classList.add('hidden');
    });
    
    // 导航栏中屏幕分类选择器
    const navCategoryFilter = document.getElementById('nav-category-filter');
    if (navCategoryFilter) {
        navCategoryFilter.addEventListener('change', function() {
            filterNewsByCategory(this.value);
            updateNavCategoryButtons(this.value);
            document.getElementById('mobile-category-filter').value = this.value;
        });
    }
    
    // 导航栏分类按钮组事件
    document.querySelectorAll('.nav-category-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            filterNewsByCategory(category);
            updateNavCategoryButtons(category);
            updateNavCategorySelector(category);
            document.getElementById('mobile-category-filter').value = category;
        });
    });
    
    // 分页控制
    document.getElementById('prev-page').addEventListener('click', goToPrevPage);
    document.getElementById('next-page').addEventListener('click', goToNextPage);
    document.getElementById('favorites-prev-page').addEventListener('click', goToFavoritesPrevPage);
    document.getElementById('favorites-next-page').addEventListener('click', goToFavoritesNextPage);
    
    // 登录注册模态框切换
    document.getElementById('login-btn').addEventListener('click', () => showModal('login-modal'));
    document.getElementById('mobile-login-btn').addEventListener('click', () => showModal('login-modal'));
    document.getElementById('register-btn').addEventListener('click', () => showModal('register-modal'));
    document.getElementById('mobile-register-btn').addEventListener('click', () => showModal('register-modal'));
    
    document.getElementById('close-login-modal').addEventListener('click', () => hideModal('login-modal'));
    document.getElementById('close-register-modal').addEventListener('click', () => hideModal('register-modal'));
    
    // 点击模态框背景关闭登录/注册模态框
    document.getElementById('login-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            hideModal('login-modal');
        }
    });
    
    document.getElementById('register-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            hideModal('register-modal');
        }
    });
    
    document.getElementById('switch-to-register').addEventListener('click', function(e) {
        e.preventDefault();
        hideModal('login-modal');
        showModal('register-modal');
    });
    
    document.getElementById('switch-to-login').addEventListener('click', function(e) {
        e.preventDefault();
        hideModal('register-modal');
        showModal('login-modal');
    });
    
    // 用户菜单
    document.getElementById('user-btn').addEventListener('click', function() {
        document.getElementById('dropdown-menu').classList.toggle('hidden');
    });
    
    // 点击其他区域关闭下拉菜单
    document.addEventListener('click', function(e) {
        const userBtn = document.getElementById('user-btn');
        const dropdown = document.getElementById('dropdown-menu');
        if (!userBtn.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });
    
    // 关闭新闻详情模态框
    document.getElementById('close-detail-modal').addEventListener('click', () => {
        hideModal('news-detail-modal');
    });
    
    // 点击模态框背景关闭详情页面
    document.getElementById('news-detail-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            hideModal('news-detail-modal');
        }
    });
    
    // 生成摘要按钮
    document.getElementById('generate-summary-btn').addEventListener('click', generateSummary);
    
    // 收藏切换按钮
    document.getElementById('favorite-toggle-btn').addEventListener('click', toggleFavorite);
    
    // 登录表单提交
    document.getElementById('login-form').addEventListener('submit', function(e) {
        e.preventDefault();
        handleLogin();
    });
    
    // 注册表单提交
    document.getElementById('register-form').addEventListener('submit', function(e) {
        e.preventDefault();
        handleRegister();
    });
    
    // 登出
    // 排序切换
    const sortByDateBtn = document.getElementById('sort-by-date');
    const sortByHotBtn = document.getElementById('sort-by-hot');
    if (sortByDateBtn && sortByHotBtn) {
        sortByDateBtn.addEventListener('click', () => {
            currentSortBy = 'date';
            sortByDateBtn.classList.add('bg-primary', 'text-white');
            sortByHotBtn.classList.remove('bg-primary', 'text-white');
            const category = getCurrentCategoryFromURL();
            reachedEnd = false; isLoadingMore = false; currentPage = 1;
            loadNews(1, category);
        });
        sortByHotBtn.addEventListener('click', () => {
            currentSortBy = 'hot';
            sortByHotBtn.classList.add('bg-primary', 'text-white');
            sortByDateBtn.classList.remove('bg-primary', 'text-white');
            const category = getCurrentCategoryFromURL();
            reachedEnd = false; isLoadingMore = false; currentPage = 1;
            loadNews(1, category);
        });
    }

    // 无限下拉加载
    const sentinel = document.getElementById('infinite-scroll-sentinel');
    if ('IntersectionObserver' in window && sentinel) {
        const io = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (entry.isIntersecting && !isLoadingMore && !reachedEnd && currentView === 'news' && !searchMode) {
                    isLoadingMore = true;
                    const category = getCurrentCategoryFromURL();
                    loadNews(currentPage + 1, category);
                }
            });
        }, { rootMargin: '200px' });
        io.observe(sentinel);
    } else {
        window.addEventListener('scroll', () => {
            if (isLoadingMore || reachedEnd || currentView !== 'news' || searchMode) return;
            const scrollBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 200;
            if (scrollBottom) {
                isLoadingMore = true;
                const category = getCurrentCategoryFromURL();
                loadNews(currentPage + 1, category);
            }
        });
    }
    document.getElementById('logout-btn').addEventListener('click', handleLogout);
    // 推荐相关事件
    const recPrev = document.getElementById('recommendations-prev');
    const recNext = document.getElementById('recommendations-next');
    const recRefresh = document.getElementById('recommendations-refresh');
    if (recPrev) recPrev.addEventListener('click', () => { if (recPage > 1) loadRecommendations(recPage - 1); });
    if (recNext) recNext.addEventListener('click', () => { if (recPage < recTotalPages) loadRecommendations(recPage + 1); });
    if (recRefresh) recRefresh.addEventListener('click', () => loadRecommendations(recPage, true)); // 刷新时传递refresh参数
    
    // 搜索相关事件监听器
    document.getElementById('search-btn').addEventListener('click', performQuickSearch);
    document.getElementById('mobile-search-btn').addEventListener('click', () => {
        performMobileSearch();
        document.getElementById('mobile-menu').classList.add('hidden');
    });
    
    // 搜索输入框回车事件
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performQuickSearch();
        }
    });
    
    // 移动端搜索输入框回车事件
    document.getElementById('mobile-search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performMobileSearch();
            document.getElementById('mobile-menu').classList.add('hidden');
        }
    });
    
    // 搜索输入框输入事件（实时搜索建议）
    document.getElementById('search-input').addEventListener('input', function(e) {
        const keyword = e.target.value.trim();
        getSearchSuggestions(keyword);
    });
    
    // 点击其他区域隐藏搜索建议
    document.addEventListener('click', function(e) {
        const searchContainer = document.getElementById('search-container');
        if (!searchContainer || !searchContainer.contains(e.target)) {
            hideSearchSuggestions();
        }
    });
    
    // 高级搜索
    document.getElementById('advanced-search-btn').addEventListener('click', () => {
        console.log('点击高级搜索按钮');
        showModal('advanced-search-modal');
        if (currentUser) {
            console.log('用户已登录，加载搜索历史');
            loadSearchHistory();
        }
        console.log('开始加载热门搜索');
        loadPopularSearches();
    });
    
    document.getElementById('close-advanced-search').addEventListener('click', () => {
        hideModal('advanced-search-modal');
    });
    
    // 点击模态框背景关闭高级搜索模态框
    document.getElementById('advanced-search-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            hideModal('advanced-search-modal');
        }
    });
    
    // 高级搜索表单提交
    document.getElementById('advanced-search-form').addEventListener('submit', function(e) {
        e.preventDefault();
        performAdvancedSearch();
    });
    
    // 清空搜索表单
    document.getElementById('clear-search-form').addEventListener('click', function() {
        console.log('清空高级搜索表单');
        document.getElementById('advanced-search-form').reset();
        // 重新加载热门搜索
        loadPopularSearches();
    });
    
    // 搜索分页控制
    document.getElementById('search-prev-page').addEventListener('click', goToSearchPrevPage);
    document.getElementById('search-next-page').addEventListener('click', goToSearchNextPage);
    
    // 搜索结果页面按钮
    document.getElementById('back-to-news').addEventListener('click', () => switchToNewsView());
    document.getElementById('modify-search').addEventListener('click', () => {
        hideModal('news-detail-modal');
        showModal('advanced-search-modal');
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const modals = ['news-detail-modal', 'login-modal', 'register-modal', 'advanced-search-modal'];
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (modal && !modal.classList.contains('hidden')) {
                    hideModal(modalId);
                }
            });
        }
    });
}

// 检查登录状态
function checkLoginStatus() {
    fetch('/api/user')
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('未登录');
        })
        .then(data => {
            if (data.status === 'success') {
                currentUser = data.user;
                updateUserInterface();
            }
        })
        .catch(error => {
            currentUser = null;
            updateUserInterface();
        });
}

// 更新用户界面（登录/未登录状态）
function updateUserInterface() {
    const loginBtn = document.getElementById('login-btn');
    const registerBtn = document.getElementById('register-btn');
    const mobileLoginBtn = document.getElementById('mobile-login-btn');
    const mobileRegisterBtn = document.getElementById('mobile-register-btn');
    const userMenu = document.getElementById('user-menu');
    const usernameDisplay = document.getElementById('username-display');
    const favoritesLink = document.getElementById('favorites-link');
    const favoritesBtn = document.getElementById('favorites-btn');
    const mobileFavoritesBtn = document.getElementById('mobile-favorites-btn');
    
    if (currentUser) {
        // 已登录状态 - 隐藏登录和注册按钮
        if (loginBtn) loginBtn.style.display = 'none';
        if (registerBtn) registerBtn.style.display = 'none';
        if (mobileLoginBtn) mobileLoginBtn.style.display = 'none';
        if (mobileRegisterBtn) mobileRegisterBtn.style.display = 'none';
        if (userMenu) userMenu.classList.remove('hidden');
        if (usernameDisplay) usernameDisplay.textContent = currentUser.username;
        
        // 显示收藏功能
        if (favoritesLink) favoritesLink.classList.remove('hidden');
        if (favoritesBtn) favoritesBtn.classList.remove('hidden');
        if (mobileFavoritesBtn) mobileFavoritesBtn.classList.remove('hidden');
        // 根据当前分类决定是否显示推荐
        const currentCategory = getCurrentCategoryFromURL();
        const recSection = document.getElementById('recommendations-section');
        const divider = document.getElementById('recommendations-divider');
        if (currentCategory === 'all') {
            if (recSection) {
                recSection.classList.remove('hidden');
                if (divider) divider.classList.remove('hidden');
                loadRecommendations(1);
            }
        } else {
            if (recSection) recSection.classList.add('hidden');
            if (divider) divider.classList.add('hidden');
        }
    } else {
        // 未登录状态 - 显示登录和注册按钮
        if (loginBtn) loginBtn.style.display = 'block';
        if (registerBtn) registerBtn.style.display = 'block';
        if (mobileLoginBtn) mobileLoginBtn.style.display = 'block';
        if (mobileRegisterBtn) mobileRegisterBtn.style.display = 'block';
        if (userMenu) userMenu.classList.add('hidden');
        
        // 隐藏收藏功能
        if (favoritesLink) favoritesLink.classList.add('hidden');
        if (favoritesBtn) favoritesBtn.classList.add('hidden');
        if (mobileFavoritesBtn) mobileFavoritesBtn.classList.add('hidden');
        // 隐藏推荐
        const recSection = document.getElementById('recommendations-section');
        const divider = document.getElementById('recommendations-divider');
        if (recSection) recSection.classList.add('hidden');
        if (divider) divider.classList.add('hidden');
        
        // 如果当前在收藏页面，切换到新闻页面
        if (currentView === 'favorites') {
            switchToNewsView();
        }
    }
}

function initRecommendationsIfNeeded() {
    if (currentUser) {
        const currentCategory = getCurrentCategoryFromURL();
        // 只有在“全部”分类时才显示推荐
        if (currentCategory === 'all') {
            const recSection = document.getElementById('recommendations-section');
            const divider = document.getElementById('recommendations-divider');
            if (recSection) {
                recSection.classList.remove('hidden');
                if (divider) divider.classList.remove('hidden');
                loadRecommendations(1);
            }
        } else {
            // 非“全部”分类时隐藏推荐
            const recSection = document.getElementById('recommendations-section');
            const divider = document.getElementById('recommendations-divider');
            if (recSection) recSection.classList.add('hidden');
            if (divider) divider.classList.add('hidden');
        }
    }
}

// 根据分类切换推荐栏目的显示状态
function toggleRecommendationsSection(category) {
    if (!currentUser) return; // 未登录用户不显示推荐
    
    const recSection = document.getElementById('recommendations-section');
    const divider = document.getElementById('recommendations-divider');
    
    if (category === 'all') {
        // “全部”分类时显示推荐
        if (recSection) {
            recSection.classList.remove('hidden');
            if (divider) divider.classList.remove('hidden');
            // 如果推荐数据为空，则加载推荐
            if (recommendations.length === 0) {
                loadRecommendations(1);
            }
        }
    } else {
        // 其他分类时隐藏推荐
        if (recSection) recSection.classList.add('hidden');
        if (divider) divider.classList.add('hidden');
    }
}

function loadRecommendations(page = 1, refresh = false) {
    // 检查当前分类，只有在"全部"分类时才加载推荐
    const currentCategory = getCurrentCategoryFromURL();
    if (currentCategory !== 'all') {
        console.log('非全部分类，跳过推荐加载');
        return;
    }
    
    const container = document.getElementById('recommendations-container');
    if (!container) return;
    recPage = page;
    container.innerHTML = '<div class="col-span-full text-center py-6 text-neutral text-sm">正在加载推荐...</div>';
    
    // 构建请求URL
    let url = `/api/recommendations?page=${page}&per_page=${recPageSize}&explain=false`;
    if (refresh) {
        url += '&refresh=true';
    }
    
    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data.status !== 'success') throw new Error(data.message || '加载失败');
            recommendations = data.recommendations || [];
            recTotal = data.pagination?.total || recommendations.length;
            recTotalPages = data.pagination?.pages || 1;
            renderRecommendations();
            updateRecommendationsControls();
        })
        .catch(err => {
            console.error('加载推荐失败', err);
            container.innerHTML = '<div class="col-span-full text-center py-6 text-red-500 text-sm">加载推荐失败</div>';
        });
}

function updateRecommendationsControls() {
    const prev = document.getElementById('recommendations-prev');
    const next = document.getElementById('recommendations-next');
    const showRange = document.getElementById('recommendations-showing-range');
    const totalEl = document.getElementById('recommendations-total');
    
    if (prev) prev.disabled = recPage <= 1;
    
    // 基于实际展示的推荐数量计算显示范围
    const actualRecommendations = recommendations.length;
    let start, end;
    
    if (actualRecommendations === 0) {
        start = 0;
        end = 0;
    } else {
        start = (recPage - 1) * recPageSize + 1;
        end = (recPage - 1) * recPageSize + actualRecommendations;
    }
    
    if (showRange) showRange.textContent = `${start}-${end}`;
    
    // 智能调整总数和页数
    let displayTotal = recTotal;
    let shouldDisableNext = recPage >= recTotalPages;
    
    // 如果当前页面推荐数量不足，更新总数和页数
    if (actualRecommendations < recPageSize) {
        if (recPage === 1) {
            // 第一页就不满，总数就是当前数量
            displayTotal = actualRecommendations;
            recTotal = actualRecommendations;
            recTotalPages = 1;
            shouldDisableNext = true;
        } else {
            // 非第一页不满，说明已经到底了
            displayTotal = end;
            recTotal = end;
            recTotalPages = Math.ceil(displayTotal / recPageSize);
            shouldDisableNext = true;
        }
    } else if (actualRecommendations === 0 && recPage > 1) {
        // 当前页面无推荐且不是第一页，说明已经超出范围
        displayTotal = (recPage - 1) * recPageSize;
        recTotal = displayTotal;
        recTotalPages = Math.ceil(displayTotal / recPageSize);
        shouldDisableNext = true;
    }
    
    if (next) next.disabled = shouldDisableNext;
    if (totalEl) totalEl.textContent = displayTotal;
}

function renderRecommendations() {
    const container = document.getElementById('recommendations-container');
    container.innerHTML = '';
    if (!recommendations.length) {
        container.innerHTML = '<div class="col-span-full text-center py-6 text-neutral text-sm">暂无推荐，试着多收藏几条新闻～</div>';
        return;
    }
    recommendations.forEach(n => container.appendChild(createNewsCard(n)));
}



// 加载新闻（支持分页）
function loadNews(page = 1, category = 'all') {
    console.log('loadNews called with page:', page, 'category:', category);
    
    // 显示加载状态
    const container = document.getElementById('news-container');
    if (!container) {
        console.error('news-container element not found!');
        return;
    }
    
    if (page === 1) {
        container.innerHTML = `
            <div class="col-span-full flex justify-center items-center py-16">
                <div class="text-center">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mb-4"></div>
                    <p class="text-neutral">正在加载新闻...</p>
                </div>
            </div>
        `;
    } else {
        // 追加模式：显示底部loading，不清空已有内容
        const loading = document.createElement('div');
        loading.id = 'infinite-loading';
        loading.className = 'col-span-full flex justify-center items-center py-6';
        loading.innerHTML = '<div class="inline-block animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-primary mr-2"></div><span class="text-neutral text-sm">加载中...</span>';
        container.appendChild(loading);
    }
    
    // 构建请求URL，包含分页和分类参数
    let url = `/api/news?page=${page}&per_page=${pageSize}`;
    if (currentSortBy && currentSortBy !== 'date') {
        url += `&sort_by=${encodeURIComponent(currentSortBy)}`;
    }
    if (category !== 'all') {
        url += `&category=${encodeURIComponent(category)}`;
    }
    console.log('Fetching URL:', url);
    
    fetch(url)
        .then(response => {
            console.log('Response status:', response.status, response.statusText);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: 获取新闻失败`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Received data:', data);
            
            if (!data || !data.news) {
                throw new Error('无效的响应数据格式');
            }
            
            // 更新总新闻数和总页数
            totalNewsCount = data.pagination ? data.pagination.total : 0;
            totalPages = data.pagination ? data.pagination.pages : 0;
            currentPage = data.pagination ? data.pagination.page : 1;
            
            console.log('Updated pagination:', { totalNewsCount, totalPages, currentPage });
            
            if (page === 1) {
                allNews = data.news;
            } else {
                allNews = allNews.concat(data.news);
            }
            filteredNews = [...allNews];
            
            console.log('News count:', filteredNews.length);
            
            renderNews(page > 1);
            updateNewsStats();
            updatePaginationControls();
            reachedEnd = (currentPage >= totalPages);
            isLoadingMore = false;
            const loadingEl = document.getElementById('infinite-loading');
            if (loadingEl) loadingEl.remove();
        })
        .catch(error => {
            console.error('加载新闻错误:', error);
            if (page === 1) {
                container.innerHTML = `
                    <div class="col-span-full text-center py-16">
                        <p class="text-red-500">加载新闻失败: ${error.message}</p>
                        <button onclick="loadNews(1, 'all')" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition">重试</button>
                    </div>
                `;
            }
            isLoadingMore = false;
            const loadingEl = document.getElementById('infinite-loading');
            if (loadingEl) loadingEl.remove();
        });
}

// 渲染新闻列表
function renderNews(append = false) {
    const container = document.getElementById('news-container');
    if (!append) container.innerHTML = '';
    
    if (filteredNews.length === 0) {
        container.innerHTML = `
            <div class="col-span-full text-center py-16">
                <p class="text-neutral">没有找到相关新闻</p>
            </div>
        `;
        return;
    }
    
    const startIndex = append ? Math.max(allNews.length - (allNews.length % pageSize || pageSize), 0) : 0;
    filteredNews.slice(startIndex).forEach(news => {
        const card = createNewsCard(news);
        container.appendChild(card);
    });
}

// 创建新闻卡片
function createNewsCard(news) {
    const card = document.createElement('div');
    card.className = 'bg-white rounded-xl shadow-sm overflow-hidden card-hover';
    card.setAttribute('data-id', news.id);
    
    // 格式化日期（优先使用原文发布时间）
    const date = new Date(news.display_publish_time || news.published_date || news.created_at);
    const formattedDate = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    // 收藏状态
    const isFavorited = news.is_favorited === 1;
    const favoriteIcon = isFavorited ? 'fa-heart' : 'fa-heart-o';
    const favoriteColor = isFavorited ? 'text-red-500' : 'text-gray-400';
    
    // 卡片内容
    card.innerHTML = `
        <div class="p-5">
            <div class="flex items-center justify-between text-xs text-neutral mb-3">
                <div class="flex items-center">
                    <span>${news.source_name || '未知来源'}</span>
                    <span class="mx-2">•</span>
                    <span>${formattedDate}</span>
                    <span class="ml-2 px-2 py-0.5 bg-light rounded-full">${getCategoryName(news.category)}</span>
                </div>
                ${currentUser ? `
                    <button class="favorite-btn hover:scale-110 transition-transform" data-news-id="${news.id}">
                        <i class="fa ${favoriteIcon} ${favoriteColor} text-lg"></i>
                    </button>
                ` : ''}
            </div>
            <div class="flex items-center text-[11px] text-gray-500 mb-2">
                <span class="mr-3"><i class="fa fa-fire text-orange-500 mr-1"></i>${news.hot_score ?? 0}</span>
                <span class="mr-3"><i class="fa fa-eye mr-1"></i>${news.views ?? 0}</span>
                <span><i class="fa fa-heart mr-1 text-red-500"></i>${news.favorites_count ?? 0}</span>
            </div>
            <h3 class="font-semibold text-lg mb-2 line-clamp-2 hover:text-primary transition cursor-pointer news-title">
                ${news.title}
            </h3>
            <p class="text-neutral text-sm mb-4 line-clamp-3">
                ${news.summary || (news.content ? news.content.substring(0, 100) + '...' : '无内容')}
            </p>
            <button class="text-primary text-sm hover:underline view-detail-btn">
                查看详情 <i class="fa fa-angle-right ml-1"></i>
            </button>
        </div>
    `;
    
    // 绑定查看详情事件
    card.querySelector('.view-detail-btn').addEventListener('click', () => showNewsDetail(news.id));
    card.querySelector('.news-title').addEventListener('click', () => showNewsDetail(news.id));
    
    // 绑定收藏按钮事件（如果用户已登录）
    if (currentUser) {
        card.querySelector('.favorite-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            toggleNewsFavorite(news.id, e.target.closest('.favorite-btn'));
        });
    }
    
    return card;
}

// 上一页
function goToPrevPage() {
    if (currentPage > 1) {
        const currentCategory = getCurrentCategoryFromURL();
        const newPage = currentPage - 1;
        
        // 更新URL参数
        const url = new URL(window.location);
        url.searchParams.set('page', newPage);
        window.history.pushState({}, '', url);
        
        loadNews(newPage, currentCategory);
        // 滚动到新闻列表顶部
        document.getElementById('news-container').scrollIntoView({ behavior: 'smooth' });
    }
}

// 下一页
function goToNextPage() {
    if (currentPage < totalPages) {
        const currentCategory = getCurrentCategoryFromURL();
        const newPage = currentPage + 1;
        
        // 更新URL参数
        const url = new URL(window.location);
        url.searchParams.set('page', newPage);
        window.history.pushState({}, '', url);
        
        loadNews(newPage, currentCategory);
        // 滚动到新闻列表顶部
        document.getElementById('news-container').scrollIntoView({ behavior: 'smooth' });
    }
}

// 更新分页控制状态
function updatePaginationControls() {
    const prevBtn = document.getElementById('prev-page');
    const nextBtn = document.getElementById('next-page');
    const showingRange = document.getElementById('showing-range');
    const totalNews = document.getElementById('total-news');
    
    // 更新按钮状态
    prevBtn.disabled = currentPage <= 1;
    nextBtn.disabled = currentPage >= totalPages;
    
    // 更新显示范围
    const start = (currentPage - 1) * pageSize + 1;
    const end = Math.min(currentPage * pageSize, totalNewsCount);
    showingRange.textContent = `${start}-${end}`;
    totalNews.textContent = totalNewsCount;
}

// 按分类筛选新闻
function filterNewsByCategory(category) {
    // 更新URL参数
    const url = new URL(window.location);
    if (category === 'all') {
        url.searchParams.delete('category');
    } else {
        url.searchParams.set('category', category);
    }
    url.searchParams.delete('page'); // 重置到第一页
    window.history.pushState({}, '', url);
    
    // 根据分类显示或隐藏推荐栏目
    toggleRecommendationsSection(category);
    
    // 重置到第一页并加载新闻
    loadNews(1, category);
}

// 从 URL 获取当前分类
function getCurrentCategoryFromURL() {
    const params = new URLSearchParams(window.location.search);
    return params.get('category') || 'all';
}

// 从 URL 获取当前页码
function getCurrentPageFromURL() {
    const params = new URLSearchParams(window.location.search);
    return parseInt(params.get('page')) || 1;
}

// 更新分类选择器状态
function updateCategorySelectors(category) {
    updateNavCategoryButtons(category);
    updateNavCategorySelector(category);
    document.getElementById('mobile-category-filter').value = category;
}

// 更新导航栏分类按钮状态
function updateNavCategoryButtons(activeCategory) {
    document.querySelectorAll('.nav-category-btn').forEach(btn => {
        const btnCategory = btn.getAttribute('data-category');
        if (btnCategory === activeCategory) {
            // 激活状态
            btn.classList.remove('bg-gray-100', 'text-gray-700');
            btn.classList.add('bg-primary', 'text-white');
        } else {
            // 非激活状态
            btn.classList.remove('bg-primary', 'text-white');
            btn.classList.add('bg-gray-100', 'text-gray-700');
        }
    });
}

// 更新导航栏中屏幕分类选择器状态
function updateNavCategorySelector(category) {
    const navCategoryFilter = document.getElementById('nav-category-filter');
    if (navCategoryFilter) {
        navCategoryFilter.value = category;
    }
}

// 显示新闻详情
function showNewsDetail(newsId) {
    // 优先在当前显示的数据中查找新闻
    let news = null;
    
    // 如果在搜索模式，先从搜索结果中查找
    if (searchMode && searchResults.length > 0) {
        news = searchResults.find(item => item.id === newsId);
    }
    
    // 如果不在搜索模式或搜索结果中没找到，从所有新闻中查找
    if (!news) {
        news = allNews.find(item => item.id === newsId);
    }
    
    // 如果还是没找到，从推荐列表中查找
    if (!news && recommendations.length > 0) {
        news = recommendations.find(item => item.id === newsId);
    }
    
    // 如果还是没找到，从收藏列表中查找
    if (!news && currentView === 'favorites') {
        news = allFavorites.find(item => item.id === newsId);
    }
    
    // 如果还是没有找到，尝试从服务器加载
    if (!news) {
        fetch(`/api/news?page=1&per_page=${totalNewsCount}`)
            .then(response => response.json())
            .then(data => {
                allNews = data.news;
                news = allNews.find(item => item.id === newsId);
                if (news) {
                    displayNewsDetail(news);
                } else {
                    alert('无法找到该新闻详情');
                }
            })
            .catch(error => {
                console.error('加载新闻详情失败:', error);
                alert('加载新闻详情失败');
            });
        return;
    }
    
    displayNewsDetail(news);
}

// 显示新闻详情
function displayNewsDetail(news) {
    currentNewsDetail = news;
    
    // 填充详情内容
    document.getElementById('detail-title').textContent = news.title;
    document.getElementById('detail-source').textContent = news.source_name || '未知来源';
    document.getElementById('detail-category').textContent = getCategoryName(news.category);
    
    // 格式化日期（优先使用原文发布时间）
    const date = new Date(news.display_publish_time || news.published_date || news.created_at);
    document.getElementById('detail-date').textContent = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    // 显示基本内容
    document.getElementById('brief-content').innerHTML = news.content || '<p class="text-gray-500">无基本内容</p>';
    document.getElementById('detail-link').href = news.link || '#';
    
    // 重置完整内容区域
    document.getElementById('full-content-section').classList.remove('hidden');
    document.getElementById('full-content-loading').classList.remove('hidden');
    document.getElementById('full-content').classList.add('hidden');
    document.getElementById('full-content-error').classList.add('hidden');
    
    // 隐藏缓存指示器
    const cacheIndicator = document.getElementById('cache-indicator');
    if (cacheIndicator) {
        cacheIndicator.classList.add('hidden');
    }
    
    // 初始隐藏生成摘要按钮，直到完整内容加载完成
    document.getElementById('generate-summary-btn').style.display = 'none';
    
    // 摘要处理
    const summaryContainer = document.getElementById('detail-summary');
    const summaryContent = document.getElementById('summary-content');
    
    if (news.summary) {
        summaryContent.textContent = news.summary;
        summaryContainer.classList.remove('hidden');
    } else {
        summaryContent.textContent = '';
        summaryContainer.classList.add('hidden');
    }
    
    // 更新收藏按钮状态
    updateFavoriteButton(news.is_favorited === 1);
    
    // 存储当前新闻ID到按钮
    document.getElementById('generate-summary-btn').setAttribute('data-news-id', news.id);
    document.getElementById('favorite-toggle-btn').setAttribute('data-news-id', news.id);
    
    // 显示模态框
    showModal('news-detail-modal');
    
    // 自动加载完整内容
    loadFullContentAutomatically(news.id);
}

// 生成新闻摘要（基于完整内容）
function generateSummary() {
    const newsId = document.getElementById('generate-summary-btn').getAttribute('data-news-id') || currentNewsDetail?.id;
    if (!newsId) {
        alert('无法获取新闻ID');
        return;
    }
    
    const btn = document.getElementById('generate-summary-btn');
    const originalHTML = btn.innerHTML;
    
    // 显示加载状态
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i>生成中...';
    
    fetch('/api/generate-summary', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ news_id: newsId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            // 更新摘要显示
            document.getElementById('summary-content').textContent = data.summary;
            document.getElementById('detail-summary').classList.remove('hidden');
            
            // 更新内存中的新闻数据
            if (currentNewsDetail) {
                currentNewsDetail.summary = data.summary;
            }
            
            // 更新按钮文本
            btn.innerHTML = '<i class="fa fa-check mr-1"></i>摘要已生成';
            btn.disabled = true;
        } else {
            alert(data.message || '生成摘要失败');
            btn.innerHTML = originalHTML;
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('生成摘要错误:', error);
        alert('生成摘要失败，请稍后重试');
        btn.innerHTML = originalHTML;
        btn.disabled = false;
    });
}

// 自动加载完整内容
function loadFullContentAutomatically(newsId) {
    if (!newsId) {
        console.error('无法获取新闻ID');
        return;
    }
    
    // 先检查缓存
    const cachedContent = getCachedContent(newsId);
    if (cachedContent) {
        console.log('使用缓存的内容:', newsId);
        // 隐藏加载状态
        document.getElementById('full-content-loading').classList.add('hidden');
        
        // 显示缓存的内容
        document.getElementById('full-content').innerHTML = cachedContent;
        document.getElementById('full-content').classList.remove('hidden');
        
        // 显示缓存指示器
        const cacheIndicator = document.getElementById('cache-indicator');
        if (cacheIndicator) {
            cacheIndicator.classList.remove('hidden');
            // 3秒后隐藏指示器
            setTimeout(() => {
                cacheIndicator.classList.add('hidden');
            }, 3000);
        }
        
        // 更新生成摘要按钮
        updateSummaryButton();
        return;
    }
    
    // 如果没有缓存，从服务器获取
    console.log('从服务器获取内容:', newsId);
    fetch('/api/news/full-content', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ news_id: newsId })
    })
    .then(response => response.json())
    .then(data => {
        // 隐藏加载状态
        document.getElementById('full-content-loading').classList.add('hidden');
        
        if (data.status === 'success') {
            // 缓存内容
            setCachedContent(newsId, data.full_content);
            
            // 显示完整内容（支持HTML格式）
            document.getElementById('full-content').innerHTML = data.full_content;
            document.getElementById('full-content').classList.remove('hidden');
            
            // 更新生成摘要按钮
            updateSummaryButton();
        } else {
            // 显示错误信息
            document.getElementById('full-content-error').classList.remove('hidden');
            document.getElementById('full-content-error').innerHTML = 
                '<p class="text-red-500 text-sm">' + (data.message || '获取完整内容失败') + '</p>';
        }
    })
    .catch(error => {
        console.error('获取完整内容错误:', error);
        // 隐藏加载状态，显示错误信息
        document.getElementById('full-content-loading').classList.add('hidden');
        document.getElementById('full-content-error').classList.remove('hidden');
        document.getElementById('full-content-error').innerHTML = 
            '<p class="text-red-500 text-sm">网络错误，获取完整内容失败</p>';
    });
}

// 更新生成摘要按钮的辅助函数
function updateSummaryButton() {
    const summaryBtn = document.getElementById('generate-summary-btn');
    if (summaryBtn) {
        // 清理原有事件监听器
        summaryBtn.removeEventListener('click', generateSummary);
        summaryBtn.removeEventListener('click', showLoginModal);
        
        if (currentUser) {
            // 已登录用户：显示生成摘要按钮
            summaryBtn.style.display = 'flex';
            summaryBtn.innerHTML = '<i class="fa fa-magic mr-1"></i><span>生成AI摘要</span>';
            summaryBtn.disabled = false;
            summaryBtn.addEventListener('click', generateSummary);
        } else {
            // 未登录用户：显示登录提示
            summaryBtn.style.display = 'flex';
            summaryBtn.innerHTML = '<i class="fa fa-lock mr-1"></i><span>登录后生成摘要</span>';
            summaryBtn.disabled = false;
            summaryBtn.addEventListener('click', showLoginModal);
        }
    }
}

// 显示登录模态框的辅助函数
function showLoginModal() {
    showModal('login-modal');
}

// 处理登录
function handleLogin() {
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;
    
    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            hideModal('login-modal');
            document.getElementById('login-form').reset();
            currentUser = data.user;
            updateUserInterface();
            // 重新加载新闻
            loadNews();
            alert('登录成功');
        } else {
            alert(data.message || '登录失败');
        }
    })
    .catch(error => {
        console.error('登录错误:', error);
        alert('登录失败，请稍后重试');
    });
}

// 处理注册
function handleRegister() {
    const username = document.getElementById('register-username').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    
    fetch('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            hideModal('register-modal');
            document.getElementById('register-form').reset();
            showModal('login-modal');
            alert('注册成功，请登录');
        } else {
            alert(data.message || '注册失败');
        }
    })
    .catch(error => {
        console.error('注册错误:', error);
        alert('注册失败，请稍后重试');
    });
}

// 处理登出
function handleLogout() {
    fetch('/api/logout', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        currentUser = null;
        updateUserInterface();
        document.getElementById('dropdown-menu').classList.add('hidden');
        // 重新加载新闻
        loadNews();
        alert('已成功登出');
    })
    .catch(error => {
        console.error('登出错误:', error);
    });
}

// 显示模态框
function showModal(id) {
    document.getElementById(id).classList.remove('hidden');
    document.body.style.overflow = 'hidden'; // 防止背景滚动
}

// 隐藏模态框
function hideModal(id) {
    document.getElementById(id).classList.add('hidden');
    document.body.style.overflow = ''; // 恢复背景滚动
}

// 更新新闻统计信息
function updateNewsStats() {
    document.getElementById('total-news-count').textContent = `${totalNewsCount} 条新闻`;
    
    // 更新最后更新时间
    if (allNews.length > 0) {
        const latestNews = allNews.reduce((latest, news) => {
            const currentDate = new Date(news.published_date || news.created_at);
            const latestDate = new Date(latest.published_date || latest.created_at);
            return currentDate > latestDate ? news : latest;
        });
        
        const latestDate = new Date(latestNews.published_date || latestNews.created_at);
        document.getElementById('last-update-time').textContent = latestDate.toLocaleString('zh-CN');
    }
}

// 获取分类中文名称
function getCategoryName(category) {
    const categoryMap = {
        'general': '综合',
        'politics': '政治',
        'economics': '财经',
        'technology': '科技',
        'society': '社会',
        'international': '国际',
        'sports': '体育',
        'entertainment': '娱乐',
        'military': '军事',
        // 兼容旧分类
        'business': '财经'
    };
    return categoryMap[category] || category;
}

// 页面切换功能
function switchToNewsView() {
    currentView = 'news';
    searchMode = false;
    currentSearchParams = {};
    
    // 显示/隐藏页面
    document.getElementById('news-page').classList.remove('hidden');
    document.getElementById('favorites-page').classList.add('hidden');
    document.getElementById('search-results-page').classList.add('hidden');
    
    // 更新标签样式
    document.getElementById('news-tab').classList.add('bg-primary', 'text-white');
    document.getElementById('news-tab').classList.remove('text-gray-500');
    document.getElementById('favorites-tab').classList.remove('bg-primary', 'text-white');
    document.getElementById('favorites-tab').classList.add('text-gray-500');
    
    // 清空搜索输入框
    document.getElementById('search-input').value = '';
    hideSearchSuggestions();
}

function switchToFavoritesView() {
    if (!currentUser) {
        alert('请先登录后再查看收藏');
        return;
    }
    
    currentView = 'favorites';
    searchMode = false;
    currentSearchParams = {};
    
    // 显示/隐藏页面
    document.getElementById('news-page').classList.add('hidden');
    document.getElementById('favorites-page').classList.remove('hidden');
    document.getElementById('search-results-page').classList.add('hidden');
    
    // 更新标签样式
    document.getElementById('favorites-tab').classList.add('bg-primary', 'text-white');
    document.getElementById('favorites-tab').classList.remove('text-gray-500');
    document.getElementById('news-tab').classList.remove('bg-primary', 'text-white');
    document.getElementById('news-tab').classList.add('text-gray-500');
    
    // 清空搜索输入框
    document.getElementById('search-input').value = '';
    hideSearchSuggestions();
    
    // 加载收藏列表
    loadFavorites();
}

// 加载收藏列表
function loadFavorites(page = 1) {
    const container = document.getElementById('favorites-container');
    container.innerHTML = `
        <div class="col-span-full flex justify-center items-center py-16">
            <div class="text-center">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mb-4"></div>
                <p class="text-neutral">正在加载收藏...</p>
            </div>
        </div>
    `;
    
    fetch(`/api/favorites?page=${page}&per_page=${pageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取收藏列表失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                totalFavoritesCount = data.pagination.total;
                totalFavoritesPages = data.pagination.pages;
                currentFavoritesPage = data.pagination.page;
                
                allFavorites = data.favorites;
                renderFavorites();
                updateFavoritesStats();
                updateFavoritesPaginationControls();
            } else {
                throw new Error(data.message || '加载收藏失败');
            }
        })
        .catch(error => {
            console.error('加载收藏错误:', error);
            container.innerHTML = `
                <div class="col-span-full text-center py-16">
                    <p class="text-red-500">加载收藏失败，请稍后重试</p>
                </div>
            `;
        });
}

// 渲染收藏列表
function renderFavorites() {
    const container = document.getElementById('favorites-container');
    container.innerHTML = '';
    
    if (allFavorites.length === 0) {
        container.innerHTML = `
            <div class="col-span-full text-center py-16">
                <div class="text-center">
                    <i class="fa fa-heart-o text-6xl text-gray-300 mb-4"></i>
                    <p class="text-neutral">您还没有收藏任何新闻</p>
                    <button onclick="switchToNewsView()" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition">
                        去看看新闻
                    </button>
                </div>
            </div>
        `;
        return;
    }
    
    allFavorites.forEach(news => {
        // 为收藏的新闻添加收藏标识
        news.is_favorited = 1;
        const card = createFavoriteCard(news);
        container.appendChild(card);
    });
}

// 创建收藏卡片（与新闻卡片类似，但包含收藏时间和取消收藏按钮）
function createFavoriteCard(news) {
    const card = document.createElement('div');
    card.className = 'bg-white rounded-xl shadow-sm overflow-hidden card-hover';
    card.setAttribute('data-id', news.id);
    
    // 格式化日期
    const date = new Date(news.published_date || news.created_at);
    const formattedDate = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    // 收藏时间
    const favoritedDate = new Date(news.favorited_at);
    const formattedFavoritedDate = favoritedDate.toLocaleString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    card.innerHTML = `
        <div class="p-5">
            <div class="flex items-center justify-between text-xs text-neutral mb-3">
                <div class="flex items-center">
                    <span>${news.source_name || '未知来源'}</span>
                    <span class="mx-2">•</span>
                    <span>${formattedDate}</span>
                    <span class="ml-2 px-2 py-0.5 bg-light rounded-full">${getCategoryName(news.category)}</span>
                </div>
                <button class="remove-favorite-btn hover:scale-110 transition-transform" data-news-id="${news.id}">
                    <i class="fa fa-heart text-red-500 text-lg"></i>
                </button>
            </div>
            <div class="text-xs text-red-500 mb-2">
                <i class="fa fa-heart mr-1"></i>收藏于 ${formattedFavoritedDate}
            </div>
            <h3 class="font-semibold text-lg mb-2 line-clamp-2 hover:text-primary transition cursor-pointer news-title">
                ${news.title}
            </h3>
            <p class="text-neutral text-sm mb-4 line-clamp-3">
                ${news.summary || (news.content ? news.content.substring(0, 100) + '...' : '无内容')}
            </p>
            <button class="text-primary text-sm hover:underline view-detail-btn">
                查看详情 <i class="fa fa-angle-right ml-1"></i>
            </button>
        </div>
    `;
    
    // 绑定事件
    card.querySelector('.view-detail-btn').addEventListener('click', () => showNewsDetail(news.id));
    card.querySelector('.news-title').addEventListener('click', () => showNewsDetail(news.id));
    card.querySelector('.remove-favorite-btn').addEventListener('click', (e) => {
        e.stopPropagation();
        removeFavoriteNews(news.id, e.target.closest('.remove-favorite-btn'));
    });
    
    return card;
}

// 收藏分页控制
function goToFavoritesPrevPage() {
    if (currentFavoritesPage > 1) {
        loadFavorites(currentFavoritesPage - 1);
        document.getElementById('favorites-container').scrollIntoView({ behavior: 'smooth' });
    }
}

function goToFavoritesNextPage() {
    if (currentFavoritesPage < totalFavoritesPages) {
        loadFavorites(currentFavoritesPage + 1);
        document.getElementById('favorites-container').scrollIntoView({ behavior: 'smooth' });
    }
}

// 更新收藏统计信息
function updateFavoritesStats() {
    document.getElementById('total-favorites-count').textContent = `${totalFavoritesCount} 条收藏`;
}

// 更新收藏分页控制
function updateFavoritesPaginationControls() {
    const prevBtn = document.getElementById('favorites-prev-page');
    const nextBtn = document.getElementById('favorites-next-page');
    const showingRange = document.getElementById('favorites-showing-range');
    const totalFavorites = document.getElementById('total-favorites');
    
    prevBtn.disabled = currentFavoritesPage <= 1;
    nextBtn.disabled = currentFavoritesPage >= totalFavoritesPages;
    
    const start = (currentFavoritesPage - 1) * pageSize + 1;
    const end = Math.min(currentFavoritesPage * pageSize, totalFavoritesCount);
    showingRange.textContent = totalFavoritesCount > 0 ? `${start}-${end}` : '0-0';
    totalFavorites.textContent = totalFavoritesCount;
}

// 收藏功能
function toggleNewsFavorite(newsId, buttonElement) {
    const icon = buttonElement.querySelector('i');
    const isFavorited = icon.classList.contains('fa-heart');
    
    if (isFavorited) {
        // 取消收藏
        removeFavoriteFromList(newsId, buttonElement);
    } else {
        // 添加收藏
        addFavoriteToList(newsId, buttonElement);
    }
}

function addFavoriteToList(newsId, buttonElement) {
    fetch('/api/favorites/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ news_id: newsId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            // 更新按钮样式
            const icon = buttonElement.querySelector('i');
            icon.classList.remove('fa-heart-o', 'text-gray-400');
            icon.classList.add('fa-heart', 'text-red-500');
            
            // 更新内存中的新闻数据
            const newsIndex = allNews.findIndex(item => item.id === parseInt(newsId));
            if (newsIndex !== -1) {
                allNews[newsIndex].is_favorited = 1;
            }
        } else {
            alert(data.message || '收藏失败');
        }
    })
    .catch(error => {
        console.error('收藏错误:', error);
        alert('收藏失败，请稍后重试');
    });
}

function removeFavoriteFromList(newsId, buttonElement) {
    fetch('/api/favorites/remove', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ news_id: newsId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            // 更新按钮样式
            const icon = buttonElement.querySelector('i');
            icon.classList.remove('fa-heart', 'text-red-500');
            icon.classList.add('fa-heart-o', 'text-gray-400');
            
            // 更新内存中的新闻数据
            const newsIndex = allNews.findIndex(item => item.id === parseInt(newsId));
            if (newsIndex !== -1) {
                allNews[newsIndex].is_favorited = 0;
            }
            
            // 如果当前在收藏页面，重新加载收藏列表
            if (currentView === 'favorites') {
                loadFavorites(currentFavoritesPage);
            }
        } else {
            alert(data.message || '取消收藏失败');
        }
    })
    .catch(error => {
        console.error('取消收藏错误:', error);
        alert('取消收藏失败，请稍后重试');
    });
}

function removeFavoriteNews(newsId, buttonElement) {
    if (confirm('确认要取消收藏这条新闻吗？')) {
        removeFavoriteFromList(newsId, buttonElement);
    }
}

// 新闻详情模态框中的收藏功能
function toggleFavorite() {
    if (!currentUser) {
        alert('请先登录后再进行收藏操作');
        return;
    }
    
    // 动态获取按钮元素，防止DOM重新创建导致的引用失效
    const getButton = () => document.getElementById('favorite-toggle-btn');
    let btn = getButton();
    
    if (!btn) {
        console.error('收藏按钮元素未找到');
        return;
    }
    
    const newsId = btn.getAttribute('data-news-id');
    if (!newsId || !currentNewsDetail) {
        console.error('收藏操作失败: 缺少必要参数', { newsId, currentNewsDetail });
        return;
    }
    
    const isFavorited = currentNewsDetail.is_favorited === 1;
    
    console.log('收藏操作开始:', {
        newsId,
        isFavorited,
        currentUser: currentUser?.username
    });
    
    // 保存原始按钮状态
    const originalIcon = btn.querySelector('i');
    const originalText = btn.querySelector('span');
    const originalIconClass = originalIcon ? originalIcon.className : '';
    const originalTextContent = originalText ? originalText.textContent : '';
    
    // 显示加载状态
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>处理中...';
    
    const apiUrl = isFavorited ? '/api/favorites/remove' : '/api/favorites/add';
    console.log('发送请求到:', apiUrl);
    
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ news_id: newsId })
    })
    .then(response => {
        console.log('HTTP响应:', {
            status: response.status,
            statusText: response.statusText,
            ok: response.ok
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('收藏操作响应:', data); 
        
        if (data.status === 'success') {
            // 更新收藏状态
            const newFavoriteStatus = isFavorited ? 0 : 1;
            currentNewsDetail.is_favorited = newFavoriteStatus;
            
            console.log('更新收藏状态:', {
                from: isFavorited,
                to: newFavoriteStatus
            });
            
            // 更新内存中的新闻数据
            const newsIndex = allNews.findIndex(item => item.id === parseInt(newsId));
            if (newsIndex !== -1) {
                allNews[newsIndex].is_favorited = newFavoriteStatus;
                console.log('更新allNews中的数据成功');
            } else {
                console.warn('在allNews中未找到对应新闻:', newsId);
            }
            
            // 更新按钮状态（在成功后执行）
            const currentBtn = getButton();
            if (currentBtn) {
                // 重建按钮的HTML结构
                if (newFavoriteStatus === 1) {
                    currentBtn.innerHTML = '<i id="favorite-icon" class="fa fa-heart mr-2"></i><span id="favorite-text">已收藏</span>';
                    currentBtn.classList.add('border-red-500', 'text-red-500');
                    currentBtn.classList.remove('border-gray-300');
                } else {
                    currentBtn.innerHTML = '<i id="favorite-icon" class="fa fa-heart-o mr-2"></i><span id="favorite-text">收藏</span>';
                    currentBtn.classList.remove('border-red-500', 'text-red-500');
                    currentBtn.classList.add('border-gray-300');
                }
                currentBtn.disabled = false;
            }
            
            // 更新页面上所有相关的新闻卡片
            updateNewsCardFavoriteStatus(newsId, newFavoriteStatus === 1);
            
            // 如果当前在收藏页面且取消收藏，重新加载收藏列表
            if (currentView === 'favorites' && newFavoriteStatus === 0) {
                console.log('在收藏页面取消收藏，即将重新加载列表');
                hideModal('news-detail-modal');
                loadFavorites(currentFavoritesPage);
            }
            
            console.log('收藏操作成功完成');
        } else {
            console.error('收藏操作业务失败:', data.message || '未知错误');
            alert(data.message || '操作失败');
            // 恢复按钮状态
            restoreButtonState();
        }
    })
    .catch(error => {
        console.error('收藏操作网络错误:', error);
        alert('操作失败，请稍后重试');
        // 恢复按钮状态
        restoreButtonState();
    })
    .finally(() => {
        console.log('收藏操作结束');
    });
    
    // 恢复按钮状态的内部函数
    function restoreButtonState() {
        const currentBtn = getButton(); // 重新获取按钮引用
        if (currentBtn) {
            // 恢复为原始状态
            if (isFavorited) {
                currentBtn.innerHTML = '<i id="favorite-icon" class="fa fa-heart mr-2"></i><span id="favorite-text">已收藏</span>';
                currentBtn.classList.add('border-red-500', 'text-red-500');
                currentBtn.classList.remove('border-gray-300');
            } else {
                currentBtn.innerHTML = '<i id="favorite-icon" class="fa fa-heart-o mr-2"></i><span id="favorite-text">收藏</span>';
                currentBtn.classList.remove('border-red-500', 'text-red-500');
                currentBtn.classList.add('border-gray-300');
            }
            currentBtn.disabled = false;
        }
    }
}

// 更新收藏按钮状态
function updateFavoriteButton(isFavorited) {
    const icon = document.getElementById('favorite-icon');
    const text = document.getElementById('favorite-text');
    const btn = document.getElementById('favorite-toggle-btn');
    
    // 检查元素是否存在
    if (!icon || !text || !btn) {
        console.warn('收藏按钮元素未找到:', { icon: !!icon, text: !!text, btn: !!btn });
        return;
    }
    
    if (isFavorited) {
        icon.classList.remove('fa-heart-o');
        icon.classList.add('fa-heart');
        text.textContent = '已收藏';
        btn.classList.add('border-red-500', 'text-red-500');
        btn.classList.remove('border-gray-300');
    } else {
        icon.classList.remove('fa-heart');
        icon.classList.add('fa-heart-o');
        text.textContent = '收藏';
        btn.classList.remove('border-red-500', 'text-red-500');
        btn.classList.add('border-gray-300');
    }
    
    console.log('收藏按钮状态已更新:', isFavorited ? '已收藏' : '未收藏');
}

// 更新页面上所有相关新闻卡片的收藏状态
function updateNewsCardFavoriteStatus(newsId, isFavorited) {
    // 查找所有具有该新闻ID的卡片
    const cards = document.querySelectorAll(`[data-id="${newsId}"]`);
    
    cards.forEach(card => {
        const favoriteBtn = card.querySelector('.favorite-btn');
        if (favoriteBtn) {
            const icon = favoriteBtn.querySelector('i');
            if (icon) {
                if (isFavorited) {
                    icon.classList.remove('fa-heart-o', 'text-gray-400');
                    icon.classList.add('fa-heart', 'text-red-500');
                } else {
                    icon.classList.remove('fa-heart', 'text-red-500');
                    icon.classList.add('fa-heart-o', 'text-gray-400');
                }
            }
        }
    });
    
    console.log(`已更新 ${cards.length} 个新闻卡片的收藏状态:`, isFavorited ? '已收藏' : '未收藏');
}

// 搜索相关工具函数
function loadSearchHistory() {
    if (!currentUser) return;
    
    fetch('/api/search-history')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showSearchHistory(data.history);
            }
        })
        .catch(error => {
            console.error('加载搜索历史失败:', error);
        });
}

function loadPopularSearches() {
    fetch('/api/popular-searches')
        .then(response => response.json())
        .then(data => {
            console.log('热门搜索数据:', data); // 添加调试日志
            if (data.status === 'success') {
                // 修复数据字段匹配问题
                showPopularSearches(data.popular_searches || data.searches || []);
            }
        })
        .catch(error => {
            console.error('加载热门搜索失败:', error);
        });
}

function showPopularSearches(searches) {
    const container = document.getElementById('popular-searches-list');
    if (!container) {
        console.error('找不到热门搜索容器元素: popular-searches-list');
        // 检查所有相关元素
        console.log('高级搜索模态框:', document.getElementById('advanced-search-modal'));
        console.log('高级搜索表单:', document.getElementById('advanced-search-form'));
        return;
    }
    
    console.log('显示热门搜索:', searches); // 添加调试日志
    container.innerHTML = '';
    
    if (!searches || searches.length === 0) {
        container.innerHTML = '<span class="text-gray-400 text-xs">暂无热门搜索</span>';
        return;
    }
    
    searches.forEach(search => {
        const tag = document.createElement('span');
        tag.className = 'inline-block bg-blue-100 text-blue-800 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-blue-200 transition mr-2 mb-2';
        // 修复数据字段访问问题
        const searchText = search.query || search.keyword || search.text || '';
        tag.textContent = searchText;
        tag.addEventListener('click', () => {
            const inputField = document.getElementById('adv-search-query') || document.getElementById('search-input');
            if (inputField) {
                inputField.value = searchText;
            }
            hideSearchSuggestions();
            // 如果在高级搜索模态框中，不自动执行搜索
            if (!document.getElementById('advanced-search-modal').classList.contains('hidden')) {
                return;
            }
            performQuickSearch();
        });
        container.appendChild(tag);
    });
    
    console.log('已显示', searches.length, '个热门搜索标签');
}

function saveSearchHistory(keyword) {
    if (!currentUser || !keyword) return;
    
    fetch('/api/search-history/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ keyword: keyword })
    })
    .catch(error => {
        console.error('保存搜索历史失败:', error);
    });
}